#include "configparser.h"
#include <qdir.h>

QString ConfigParser::kBasePath = PROJECT_ROOT_DIR;

bool ConfigParser::loadConfig(const QString &filePath)
{
    m_configMap.clear();

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        m_errorString = file.errorString();
        return false;
    }

    QTextStream in(&file);
    in.setEncoding(QStringConverter::Utf8);

    int lineNum = 0;
    while (!in.atEnd()) {
        lineNum++;
        QString line = in.readLine().trimmed();

        /* Ignore empty line, comment line */
        if (line.isEmpty() || line.startsWith('#') || line.startsWith(';')) {
            continue;
        }

        int equalsPos = line.indexOf('=');
        if (equalsPos != -1) {
            QString key = line.left(equalsPos).trimmed();
            QString value = line.mid(equalsPos + 1).trimmed();

            value = removeQuotes(value);

            m_configMap[key] = value;
        }
        else {
            qWarning() << "line " << lineNum << " format is wrong: " << line;
        }
    }

    file.close();
    return true;
}

QString ConfigParser::getTargetObjPath() const
{
    QString res = "";
    QString path = getValue("default_target_obj");
    QFileInfo info(path);

    if (info.isRelative()) {
        res = kBasePath + "/" + path;
    }
    else {
        res = path;
    }

    return res;
}

QString ConfigParser::removeQuotes(const QString &value)
{
    if ((value.startsWith('"') && value.endsWith('"'))
        || (value.startsWith('\'') && value.endsWith('\''))) {
        return value.mid(1, value.length() - 2);
    }
    return value;
}
